class Slider {
  constructor() {
    this.container = document.querySelector("article .container")
    this.wrapper = document.querySelector(".wrapper")
    this.pagination = document.querySelector(".pagination")
    this.navigation = document.querySelector(".navigation")
    this.paginationList = this.pagination.querySelectorAll("span")

    this.currentIndex = 0
    this.interval = 2000
    this.autoTimer = null
  }
  init() {
    let autoTimer = setInterval(this.rightMove.bind(this), this.interval)

    this.container.onmouseover = function () {
      clearInterval(autoTimer)
    }
    this.container.onmouseleave = () => {
      autoTimer = setInterval(this.rightMove.bind(this), this.interval)
    }
    this.container.addEventListener("click", this.clickEvent.bind(this))
  }
  clickEvent(e) {
    // console.log(e.target);
    //标签必须大写
    if (e.target.tagName === "I") {
      if (e.target.className === "fa left") {
        this.leftMove()
      } else {
        this.rightMove()
      }
    }
    if (e.target.tagName === "SPAN") {
      this.currentIndex = e.target.getAttribute("data-index") - 1
      this.rightMove()
    }
  }
  rightMove() {
    this.currentIndex++
    if (this.currentIndex >= 4) {
      this.wrapper.style.transitionDuration = "0ms"
      this.wrapper.style.left = "0px"
      this.currentIndex = 1
      this.wrapper.offsetLeft
    }
    this.wrapper.style.transitionDuration = "800ms"
    this.wrapper.style.left = `${-this.currentIndex * 1000}px`
    this.paginationFocus()
  }
  leftMove() {
    // console.log(paginationList.length);
    this.currentIndex--
    if (this.currentIndex < 0) {
      this.wrapper.style.transitionDuration = "0ms"
      this.wrapper.style.left = `${-paginationList.length * 1000}px`
      this.currentIndex = paginationList.length - 1
      this.wrapper.offsetLeft
    }
    this.wrapper.style.transitionDuration = "800ms"
    this.wrapper.style.left = `${-this.currentIndex * 1000}px`
    this.paginationFocus()
  }
  paginationFocus() {
    let temp = this.currentIndex
    temp === 3 ? (temp = 0) : null
    ;[].forEach.call(this.paginationList, (item, index) => {
      //添加自定义属性
      item.setAttribute(`data-index`, index)
      item.className = temp === index ? "active" : ""
    })
  }
}
export default Slider
